// 采购计划制单
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Menu, Dropdown, Input, Button, message, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
// import { Util } from 'tools'
import Moment from 'moment';
import DetailReview from './component/DetailReview.jsx';
import InquireWarehouseVoucher from './component/InquireWarehouseVoucher.jsx';
import AccordingToRequestForm from './component/AccordingToRequestForm'
import AccordingToConsume from './component/AccordingToConsume'
import AccordingToBound from './component/AccordingToBound'
import './style/index.less';
import { printPurPlan } from '../commonPrint/stkPrint';
// const { printPurPlan }=stkPrint;
import ConsumptionStatistics from './component/ConsumptionStatistics.jsx';

const { Option } = Select;
const { TextArea } = Input;

// function isObjEqual(o1, o2) {
// 	var props1 = Object.getOwnPropertyNames(o1);
// 	var props2 = Object.getOwnPropertyNames(o2);
// 	if (props1.length != props2.length) {
// 		return false;
// 	}
// 	for (var i = 0, max = props1.length; i < max; i++) {
// 		var propName = props1[i];
// 		if (o1[propName] !== o2[propName]) {
// 			return false;
// 		}
// 	}
// 	return true;
// }
const InPurPlan = Form.create()(
	class extends React.Component {
		constructor() {
			super();
			this.state = {
				userInfo: {},
				SelectData: {}, // 下拉框数据
				detailInfo: [], // 明细列表数据
				rowId: '', // 入库单Id
				tacitlyApproveData: {}, // 界面的默认数据
				pageSize: 10,
				page: 1,
				User: JSON.parse(window.sessionStorage.userData),
				statusCode: '',
				statusId: '',
				TemplateShowing: '',
				stkCatID: '',
				inOpLocDr: '',
				ChineseEnglishSize: {}, //中英翻译
			};
			this.myRef1 = React.createRef();
			this.myRef2 = React.createRef();
			this.myRef3 = React.createRef();
			this.myRef4 = React.createRef();
			this.myRef5 = React.createRef();
			this.myRef6 = React.createRef();
			this.myRef7 = React.createRef();
			this.myRef8 = React.createRef();
			this.myRef9 = React.createRef();
		}

		componentDidMount() {
			// 初始化数据
			this.getSelectData();
			this.getTacitlyApproveData();
		}

		componentWillUnmount() {
			// 组件销毁前将静止让setState修改state的状态
			this.setState = (state, callback) => { return; }
		}

		onRef = (ref) => {
			this.childModal = ref;
		};

		detailOnRef = (ref) => {
			this.childDetail = ref;
		};

		// 获取下拉框的数据
		getSelectData() {
			let data = {
				params: []
			};
			$http.post('urlS', this, {
				code: "02020080",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ SelectData: res })
					} else {
						this.setState({ SelectData: {} })
					}
				}
			});
		}

		//获取中英版
		getChineseEnglishSize = (v) => {
			this.setState({ ChineseEnglishSize: v })
		}

		// 保存
		saveHandle = () => {
			if (this.childDetail.state.data.length < 1) {
				if (this.state.User.language == 'EN') {
					message.error("Detail list cannot be empty");
				} else {
					message.error("明细列表不能为空");
				}
			} else {

				// if(this.childDetail.state.stockID){
				//     let newObj =  this.childDetail.checkFormData();
				//     let beforeObj = this.childDetail.initialDataObj();
				//     if (!isObjEqual(newObj,beforeObj)){
				//         message.error('有未保存的数据，请先保存');
				//         return
				//     }
				// }
				this.props.form.validateFields((errors, values) => {
					let obj = JSON.parse(JSON.stringify(values));
					if (errors == null) {
						let userList = this.state.userInfo ? this.state.userInfo : undefined;
						let remark = this.props.form.getFieldValue('remark2');
						let listId = this.childModal.state.rowId;
						let data = {
							params: [{
								PPID: listId ? listId : this.state.statusId ? this.state.statusId : '',
								locID: userList.LocDr ? userList.LocDr.id : obj.inOpLocDr,
								operTypeID: userList.OperTypeDr ? userList.OperTypeDr.id : obj.operType,
								stkCatID: obj.stkCat ? obj.stkCat : '',
								remark: remark ? remark : '',
								detail: this.childDetail.state.data
							}]
						};
						$http.post('urlS', this, {
							code: "02020081",
							data: data,
							success: function (res) {

								if (+res.errorCode === 0) {
									this.setState({ statusCode: res.result.main.state.id, statusId: res.result.main.PPID });
									this.childModal.setState({ tableData: [], total: 0 });
									// 成功提示
									message.success(res.errorMessage);
									this.getEchoData(res.result.main.PPID);
								}
							},
							error: function (err) {
								console.log(err)
							}
						})
					}
				})

			}

		};

		// 保存成功后根据返回回来的inOperateID重新查找数据
		getEchoData = (id) => {
			// 重置表单
			this.props.form.resetFields(); //清空所有
			this.setState({ rowId: id }); // 将行id保存起来
			let data = {
				params: [
					{
						PPID: id
					}
				],
				pagination: [
					{
						pageSize: this.state.pageSize,
						currentPage: this.state.page,
					}
				],
			};
			$http.post('urlS', this, {
				code: "02020083",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						for (let i = 0; i < res.detail.rows.length; i++) {
							res.detail.rows[i].key = i + "main";
						}
						this.setState({ userInfo: res.main, detailInfo: res.detail.rows });
						// this.props.form.setFieldsValue(res.result[0].mainInfo[0]); // 将查询出来的数据回显
					} else {
						this.setState({ userInfo: {}, detailInfo: [] });
					}
				}
			})
		}

		// 获取到入库部门的值
		getInOpLocDr() {
			let inOpLocDr = this.props.form.getFieldValue('inOpLocDr');
			this.setState({ inOpLocDr: inOpLocDr });
			return inOpLocDr
		}

		// 点击查询显示弹框
		inquireHandle = () => {
			this.getInOpLocDr();
			this.childModal.showModal();
		};

		// 重置所有内容
		resetFieldsAll() {
			this.props.form.resetFields(); //清空所有
			this.setState({ userInfo: {}, detailInfo: [], rowId: "", statusId: '', statusCode: '' });
			this.childDetail.resetFields();
			this.childDetail.deleteData();
			this.childModal.handleUncheck();
			this.childModal.setState({ tableData: [] });
		}

		// 重置表单
		resetFields = () => {
			this.resetFieldsAll()
		};

		verificationObj() {
			for (var i in this.childDetail.state.userInfo) {
				return true;
			}
			return false
		}

		// 删除
		handleDelete = () => {
			let deletDetail = this.state.statusId ? this.state.statusId : undefined;
			let data2 = {
				params: {
					detail: [{
						PPDetailID: this.childDetail.state.userInfo ? this.childDetail.state.userInfo.PPDetailID : undefined,
					}]
				}
			};
			let data3 = {
				params: {
					main: [
						{
							PPID: this.childModal.state.rowId ? this.childModal.state.rowId : deletDetail,
						}
					]
				}
			};
			$http.post('urlS', this, {
				code: "02020084",
				data: this.verificationObj() ? data2 : data3,
				success: function (res) {
					if (+res.errorCode === 0) {
						message.success(res.errorMessage);
						this.resetFieldsAll();
						this.childModal.setState({ tableData: [], total: 0 })
					}
				}
			})
		};

		// 获取界面默认值
		getTacitlyApproveData() {
			let data = {
				params: []
			};
			$http.post('urlS', this, {
				code: "02020054",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ tacitlyApproveData: res.result[0] })
					} else {
						this.setState({ tacitlyApproveData: {} })
					}
				}
			})
		}

		accomplish = () => {
			let userPPID = this.state.userInfo.PPID ? this.state.userInfo.PPID : undefined;
			let data = {
				params: [{
					PPID: this.state.statusId ? this.state.statusId : userPPID
				}]
			};
			$http.post('urlS', this, {
				code: "02020087",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						message.success(res.errorMessage);
						this.setState({ statusCode: '' });
						this.getEchoData(res.result.main.PPID);
						this.childModal.setState({ tableData: [], total: 0 })
					}
				}
			})
		};

		offAccomplish = () => {
			let userPPID = this.state.userInfo.PPID ? this.state.userInfo.PPID : undefined;
			let data = {
				params: [{
					PPID: this.state.statusId ? this.state.statusId : userPPID
				}]
			};
			$http.post('urlS', this, {
				code: "02020088",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						message.success(res.errorMessage);
						this.getEchoData(res.result.main.PPID);
						this.childModal.setState({ tableData: [], total: 0 })
					}
				}
			})
		};

		onSelectRef = (ref) => {
			this.childSelect = ref;
		};

		onConsumeRef = (ref) => {
			this.childConsume = ref;
		};

		onBoundRef = (ref) => {
			this.childBound = ref;
		};

		//显示依据请求单弹窗
		accordingRequest = () => {
			this.childSelect.showModal();
		}

		//显示依据消耗弹框
		accordingConsume = () => {
			this.childConsume.showModal();
		}

		//显示依据消耗弹框
		accordingBound = () => {
			this.childBound.showModal();
		}

		changeStkCat = (v) => {
			this.setState({ stkCatID: v, inOpLocDr: this.props.form.getFieldValue('inOpLocDr') })
		}

		changesDesc = (v) => {
			this.setState({ stkCatID: this.props.form.getFieldValue('stkCat'), inOpLocDr: v })
		}

		consumptionStatisticsRef = ref => {
			this.consumptionStatisticsChild = ref;
		}

		// 打开消耗统计弹窗
		handleShowConsumptionStatisticsModal = () => {
			this.consumptionStatisticsChild.showModal();
		}

		render() {
			let { ChineseEnglishSize } = this.state;
			const formItemInput = {
				labelCol: { span: 6 },
				wrapperCol: { span: 18 },
			};
			const { getFieldDecorator } = this.props.form;
			let userInfo = this.state.userInfo ? this.state.userInfo : {};
			let user = this.state.User.locID ? this.state.User.locID : undefined;
			let userStatusCode = this.state.userInfo.state ? this.state.userInfo.state.id : '';
			const menu = (
				<Menu>
					<Menu.Item>
						<a rel="noopener noreferrer" onClick={() => { this.accordingRequest() }} >
							{ChineseEnglishSize.purchasePlanDetailListAccordingTo ? ChineseEnglishSize.purchasePlanDetailListAccordingTo.descripts : '依据请求单'}
						</a>
					</Menu.Item>
					{/* <Menu.Item>
						<a rel="noopener noreferrer" onClick={() => { this.accordingConsume() }} >
							{ChineseEnglishSize.purchasePlanDetailListconsumption ? ChineseEnglishSize.purchasePlanDetailListconsumption.descripts : '依据消耗'}
						</a>
					</Menu.Item> */}
					<Menu.Item>
						<a rel="noopener noreferrer" onClick={this.accordingBound}>
							{ChineseEnglishSize.purchasePlanDetailListlimits ? ChineseEnglishSize.purchasePlanDetailListlimits.descripts : '依据库存上下限'}
						</a>
					</Menu.Item>
					<Menu.Item>
						<a rel="noopener noreferrer" onClick={this.handleShowConsumptionStatisticsModal}>
							消耗统计
             </a>
					</Menu.Item>
				</Menu>
			);
			return (
				<div className="inPurPlan">
					<Card
						size="small"
						title={<div className="card-title-left-icon"><div></div>{ChineseEnglishSize.purchasePlanDetailListPurchaseP ? ChineseEnglishSize.purchasePlanDetailListPurchaseP.descripts : '采购计划制单'}</div>}
					>
						<Row>
							<Col span={19} className="top-form">
								<Form>
									<Row>
										<Col span={6} style={{ paddingRight: '10px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListloc ? ChineseEnglishSize.purchasePlanDetailListloc.descripts : '科室'} {...formItemInput}>
												{getFieldDecorator('inOpLocDr', {
													initialValue: userInfo.loc ? userInfo.loc.id : user,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListloc ? ChineseEnglishSize.purchasePlanDetailListloc.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListloc ? ChineseEnglishSize.purchasePlanDetailListloc.message : '科室不能为空' }]
												})(
													<Select showSearch allowClear onChange={this.changesDesc}>
														{this.state.SelectData.loc && this.state.SelectData.loc.map(item => {
															return <Option key={item.id} value={item.id} >{item.descripts}</Option>
														})}
													</Select>
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingRight: '10px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListNO ? ChineseEnglishSize.purchasePlanDetailListNO.descripts : '计划单号'} {...formItemInput}>
												{getFieldDecorator('NO', {
													initialValue: userInfo.PPNO ? userInfo.PPNO : undefined,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListNO ? ChineseEnglishSize.purchasePlanDetailListNO.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListNO ? ChineseEnglishSize.purchasePlanDetailListNO.message : '计划单号不能为空' }]
												})(
													<Input disabled />
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingRight: '30px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListstkCat ? ChineseEnglishSize.purchasePlanDetailListstkCat.descripts : '库存大类'} {...formItemInput}>
												{getFieldDecorator('stkCat', {
													initialValue: userInfo.stkCat ? userInfo.stkCat.id : undefined,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListstkCat ? ChineseEnglishSize.purchasePlanDetailListstkCat.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListstkCat ? ChineseEnglishSize.purchasePlanDetailListstkCat.message : '库存大类不能为空' }]
												})(
													<Select showSearch allowClear placeholder={ChineseEnglishSize.purchasePlanDetailListpleaseChoose && ChineseEnglishSize.purchasePlanDetailListstkCat ? (ChineseEnglishSize.purchasePlanDetailListpleaseChoose.descripts + ChineseEnglishSize.purchasePlanDetailListstkCat.descripts) : '请选择库存大类'} onChange={this.changeStkCat}>
														{this.state.SelectData.stkCat && this.state.SelectData.stkCat.map(item => {
															return <Option key={item.id} value={item.id}>{item.descripts}</Option>
														})}
													</Select>
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingRight: '30px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListstatusDoc ? ChineseEnglishSize.purchasePlanDetailListstatusDoc.descripts : '单据状态'} {...formItemInput}>
												{getFieldDecorator('statusDoc', {
													initialValue: userInfo.state ? userInfo.state.id : undefined,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListstatusDoc ? ChineseEnglishSize.purchasePlanDetailListstatusDoc.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListstatusDoc ? ChineseEnglishSize.purchasePlanDetailListstatusDoc.message : '单据状态不能为空' }]
												})(
													<Select showSearch allowClear disabled>
														{this.state.SelectData.state && this.state.SelectData.state.map(item => {
															return <Option key={item.id} value={item.id}>{item.descripts}</Option>
														})}
													</Select>
												)}
											</Form.Item>
										</Col>
									</Row>
									<Row>
										<Col span={6} style={{ paddingRight: '10px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListStartDate ? ChineseEnglishSize.purchasePlanDetailListStartDate.descripts : '制单日期'}  {...formItemInput}>
												{getFieldDecorator('StartDate', {
													initialValue: Moment(),
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListStartDate ? ChineseEnglishSize.purchasePlanDetailListStartDate.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListNO ? ChineseEnglishSize.purchasePlanDetailListStartDate.message : '制单日期不能为空' }]
												})(
													<DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" disabled />
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingRight: '10px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListoperType ? ChineseEnglishSize.purchasePlanDetailListoperType.descripts : '采购类型'} {...formItemInput}>
												{getFieldDecorator('operType', {
													initialValue: userInfo.operType ? userInfo.operType.id : undefined,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListoperType ? ChineseEnglishSize.purchasePlanDetailListoperType.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListoperType ? ChineseEnglishSize.purchasePlanDetailListoperType.message : '采购类型不能为空' }]
												})(
													<Select showSearch allowClear placeholder={ChineseEnglishSize.purchasePlanDetailListpleaseChoose && ChineseEnglishSize.purchasePlanDetailListoperType ? (ChineseEnglishSize.purchasePlanDetailListpleaseChoose.descripts + ChineseEnglishSize.purchasePlanDetailListoperType.descripts) : '请选择库存大类'} >
														{this.state.SelectData.operType && this.state.SelectData.operType.map(item => {
															return <Option key={item.id} value={item.id} >{item.descripts}</Option>
														})}
													</Select>
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingRight: '30px' }}>
											<Form.Item label={ChineseEnglishSize.purchasePlanDetailListremark ? ChineseEnglishSize.purchasePlanDetailListremark.descripts : '备注'} {...formItemInput}>
												{getFieldDecorator('remark2', {
													initialValue: userInfo.remark ? userInfo.remark : undefined,
													rules: [{ required: ChineseEnglishSize.purchasePlanDetailListremark ? ChineseEnglishSize.purchasePlanDetailListremark.required == 'Y' ? true : false : false, message: ChineseEnglishSize.purchasePlanDetailListremark ? ChineseEnglishSize.purchasePlanDetailListremark.message : '备注不能为空' }]
												})(
													<TextArea rows={1} style={{ width: '100%' }} />
												)}
											</Form.Item>
										</Col>
										<Col span={6} style={{ paddingLeft: '85px', marginTop: '3px' }}>
											<Dropdown overlay={menu} placement="bottomLeft">
												<Button>{ChineseEnglishSize.purchasePlanDetailListPurchase ? ChineseEnglishSize.purchasePlanDetailListPurchase.descripts : '采购辅助制单'}</Button>
											</Dropdown>
										</Col>
									</Row>
								</Form>
							</Col>
							<Col span={5}>
								<Row style={{ marginBottom: '20px', marginTop: '5px' }}>
									<Button style={{ marginRight: '30px' }} onClick={this.inquireHandle}>{ChineseEnglishSize.purchasePlanDetailListsearch ? ChineseEnglishSize.purchasePlanDetailListsearch.descripts : '查询'}</Button>
									<Button type="primary" style={{ marginRight: '30px' }} onClick={this.saveHandle}>{ChineseEnglishSize.purchasePlanDetailListsave ? ChineseEnglishSize.purchasePlanDetailListsave.descripts : '保存'}</Button>
									<Button style={{ marginRight: '20px' }} disabled={this.state.statusCode == 10 ? false : userStatusCode == 10 ? false : true} onClick={this.accomplish}>{ChineseEnglishSize.purchasePlanDetailListaccomplish ? ChineseEnglishSize.purchasePlanDetailListaccomplish.descripts : '完成'}</Button>
									<Button type="dashed" onClick={printPurPlan.bind(this, this.state.rowId)}>{ChineseEnglishSize.purchasePlanDetailListprint ? ChineseEnglishSize.purchasePlanDetailListprint.descripts : '打印'}</Button>
								</Row>
								<Row>
									<Popconfirm title={this.state.User.language == 'EN' ? 'The data will be initialized after resetting. Are you sure you want to reset it?' : "重置后将初始化数据，你确定要重置吗?"} onConfirm={this.resetFields} okText={this.state.User.language == 'EN' ? "Yes" : '是'} cancelText={this.state.User.language == 'EN' ? "No" : '否'}>
										<Button style={{ marginRight: '30px' }} >{ChineseEnglishSize.purchasePlanDetailListReset ? ChineseEnglishSize.purchasePlanDetailListReset.descripts : '重置'}</Button>
									</Popconfirm>
									<Popconfirm title={this.state.User.language == 'EN' ? 'TDelete is not recoverable, are you sure you want to delete it?' : "删除不可恢复，你确定要删除吗?"} onConfirm={this.handleDelete} okText={this.state.User.language == 'EN' ? "Yes" : '是'} cancelText={this.state.User.language == 'EN' ? "No" : '否'}>
										<Button type="danger" style={{ marginRight: '30px' }}>{ChineseEnglishSize.purchasePlanDetailListdelete ? ChineseEnglishSize.purchasePlanDetailListdelete.descripts : '删除'}</Button>
									</Popconfirm>
									<Button disabled={this.state.statusCode == 20 ? false : userStatusCode == 20 ? false : true} onClick={this.offAccomplish}>{ChineseEnglishSize.purchasePlanDetailListCancel ? ChineseEnglishSize.purchasePlanDetailListCancel.descripts : '取消完成'}</Button>
								</Row>
							</Col>
						</Row>
					</Card>
					<DetailReview SelectData={this.state.SelectData} onRef={this.detailOnRef} detailInfo={this.state.detailInfo} handleThis={this} inOpLocDr={this.state.inOpLocDr} stkCatID={this.state.stkCatID} />
					<InquireWarehouseVoucher ChineseEnglishSize={this.state.ChineseEnglishSize} SelectData={this.state.SelectData} onRef={this.onRef} inOpLocDr={this.state.inOpLocDr} handleThis={this} />
					<AccordingToRequestForm ChineseEnglishSize={this.state.ChineseEnglishSize} onRef={this.onSelectRef} inOpLocDr={this.state.inOpLocDr} handleThis={this} />
					<AccordingToConsume ChineseEnglishSize={this.state.ChineseEnglishSize} onRef={this.onConsumeRef} inOpLocDr={this.state.inOpLocDr} handleThis={this} />
					<AccordingToBound ChineseEnglishSize={this.state.ChineseEnglishSize} onRef={this.onBoundRef} inOpLocDr={this.state.inOpLocDr} handleThis={this} />
					<ConsumptionStatistics onRef={this.consumptionStatisticsRef} getEchoData={this.getEchoData} />
				</div>
			)
		}
	}
);
export default InPurPlan;